import { NameSpace } from 'utils/index';
import { getCompareInfo } from 'api';
import CONSTANTS from 'utils/constants';

const ns = NameSpace('projectCompare');

export const UPDATE_DATA = ns('UPDATE_DATA');
export const UPDATE_PAGE_INFO = ns('UPDATE_PAGE_INFO');
export const COMPARISON_CHANGE = ns('COMPARISON_CHANGE');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

// 获取commits数据
export function getCommitCompare() {
  return (dispatch, getState) => {
    const state = getState().project.projectCompare;
    const { from, to, comparisonValue } = state;
    const data = {
      from,
      to,
      merge_base: comparisonValue === 'Merge comparison',
    };

    updateData({
      isLoading: true,
    })(dispatch);

    getCompareInfo(data)
      .then((res) => {
        const { commits, diffs, messages } = res;
        diffs.forEach((item) => {
          // 添加假的diff头部，此处 0299f74..23f1202 接口中没有，先写死了
          const fakeHeader = `diff --git a/${item.old_path} b/${item.new_path}\nindex 0299f74..23f1202 ${item.b_mode}\n`;
          item.diff = fakeHeader + item.diff;

          // 如果单个diff大小大于 MAX_CR_DIFF_SIZE 或 全部diff数量大于 MAX_DIFF_NUM，则不自动加载内容，让用户手动点击加载
          if (
            item.diff.length > CONSTANTS.MAX_CR_DIFF_SIZE ||
            diffs.length > CONSTANTS.MAX_DIFF_NUM
          ) {
            item.originalDiff = item.diff;
            item.diff = '$WAITING_FOR_CLICK_BIG_SIZE$';
          }
        });
        updateData({
          commits,
          diffs,
          messages,
          isLoading: false,
          fromBranch: from,
          toBranch: to,
        })(dispatch);
      })
      .catch((err) => {
        let messages = '';
        try {
          messages = JSON.parse(err.responseText).messages;
        } catch (error) {
          console.error(error);
        }
        updateData({
          isLoading: false,
          messages,
        })(dispatch);
      });
  };
}

// 切换比较模式
export function comparisonChange(data) {
  return (dispatch) => {
    dispatch({
      type: COMPARISON_CHANGE,
      data,
    });
  };
}
